from sqlalchemy import Table, or_

from common.database import db_connect
from app.config.config import config
from model.user import User

db_session,Base,engine = db_connect()
from app.settings import env

class Article(Base):
    __table__ = Table("article", Base.metadata,autoload_with=engine)
    # 查询所有文章,不要草稿1不是0是,
    def find_article(self,page,article_type="recommend"):
    # 一页显示10条内容,page默认1开始
        if int(page) < 1:
            page = 1
        count = int(page) * config[env].page_count
        # 来到推荐分类下方
        if article_type == "recommend":
            result = db_session.query(Article,User.nickname).join(
                User,User.user_id==Article.user_id
            ).filter(
                Article.drafted == 1
            ).order_by(
                Article.browse_num.desc()).limit(count).all()
        else:
            result = db_session.query(Article,User.nickname).join(
                User, User.user_id == Article.user_id
            ).filter(
                Article.label_name == article_type,
                Article.drafted == 1
            ).order_by(
                Article.browse_num.desc()).limit(count).all()

        return result

    def search_article(self,page,keyword):
        if int(page) < 1:
            page = 1
        count = int(page) * config[env].page_count
        result = db_session.query(
            Article,User.nickname).join(
            User,User.user_id==Article.user_id).filter(
            or_(Article.title.like("%"+keyword+"%"),
                Article.article_content.like("%"+keyword+"%"))
        ).order_by(
            Article.browse_num.desc()
        ).limit(count).all()
        return result
